package dyyx.bladex.util;

import java.lang.management.ClassLoadingMXBean;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.ThreadMXBean;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class JvmStatusUtil {
	
	public static Map<String,String> getStatus(){
		
		Map<String,String> map = new LinkedHashMap<String,String>();
		
		Runtime rt = Runtime.getRuntime();
		
		
		map.put("maxMemory", rt.maxMemory()+"");
		map.put("totalMemory", rt.totalMemory()+"");
		map.put("freeMemory", rt.freeMemory()+"");
		
		OperatingSystemMXBean op = ManagementFactory.getOperatingSystemMXBean(); 
		map.put("lastMinuteLoad", 	op.getSystemLoadAverage()+"");
	
		map.put("availableProcessors", rt.availableProcessors()+"");
		
		
		ThreadMXBean tmb = ManagementFactory.getThreadMXBean(); 
		
		map.put("peakThreadCount", tmb.getPeakThreadCount()+"");
		map.put("threadCount", tmb.getThreadCount()+"");
		map.put("totalStartedThreadCount", tmb.getTotalStartedThreadCount()+"");
		
	
		ClassLoadingMXBean clmb = ManagementFactory.getClassLoadingMXBean();  
		map.put("totalLoadedClassCount" ,clmb.getTotalLoadedClassCount()+"");  
		map.put("loadedClassCount",clmb.getLoadedClassCount()+"");  
		map.put("unloadedClassCount" , clmb.getUnloadedClassCount()+"");
		
		
		List<GarbageCollectorMXBean> gcmbs = ManagementFactory.getGarbageCollectorMXBeans();
		if (gcmbs != null) {
			int num = gcmbs.size();

			for (int i = 0; i < num; i++) {
				GarbageCollectorMXBean mb = gcmbs.get(i);
				String key = "gc" + i;
				StringBuilder sb = new StringBuilder();
				sb.append("name=" + mb.getName());
				sb.append(",count=" + mb.getCollectionCount());
				sb.append(",time=" + mb.getCollectionTime());
				map.put(key, sb.toString());
			}
		}
		
		List<MemoryPoolMXBean> mps = ManagementFactory.getMemoryPoolMXBeans();

		if (mps != null) {
			int num = mps.size();

			for (int i = 0; i < num; i++) {
				MemoryPoolMXBean mb = mps.get(i);
				String key = "mempool" + i;
				StringBuilder sb = new StringBuilder();
				sb.append("name=" + mb.getName());
				sb.append(",type=" + mb.getType());
				sb.append(",usage=" + mb.getCollectionUsage());

				map.put(key, sb.toString());
			}

		}
        
		return map;
	}

}
